﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Lists;
using System.Data.SqlClient;

namespace ReportGenerators
{
    public partial class FrmThamSoBaoCaoHangTheoNhaCungCap : BasicForms.FrmThamSoBaoCao
    {
        public FrmThamSoBaoCaoHangTheoNhaCungCap()
        {
            InitializeComponent();
        }

        private void FrmThamSoBaoCaoHangTheoNhaCungCap_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                #region cmbNhaCungCap
                DataView dvDoiTuongNghiepVu = DanhMucDoiTuongNghiepVu.GetAll().DataView;
                cmbDoiTuongNghiepVu.DataSource = dvDoiTuongNghiepVu;
                cmbDoiTuongNghiepVu.DisplayColumn = "Ten";
                cmbDoiTuongNghiepVu.ValueColumn = "ID";
                cmbDoiTuongNghiepVu.AddVisibleColumn("Ma", "Mã");
                cmbDoiTuongNghiepVu.AddVisibleColumn("Ten", "Tên");
                cmbDoiTuongNghiepVu.Buttons[1].Visible = false;
                #endregion

                #region cmbVatTuHangHoa
                SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT ID FROM NhomVatTuHangHoa WHERE Ma='KYGUI'", con);
                SqlDataReader dr = cmd.ExecuteReader();
                string nhomVatTuHangHoaID = "";
                string filterExpression = "";
                while (dr.Read())
                {
                    nhomVatTuHangHoaID = dr[0].ToString();
                    filterExpression = "NhomVatTuHangHoaID = '" + nhomVatTuHangHoaID + "'";
                }
                dr.Close();
                DataView dvVatTuHangHoa = DanhMucVatTuHangHoa.Instance.DataView;
                //DataView dvVatTuHangHoa = DanhMucVatTuHangHoa.Filter("NhomVatTuHangHoaID='E9D29D9C-17C5-4F5B-A488-9A07F51DEFBF'").DataView;
                cmbVatTuHangHoa.DataSource = dvVatTuHangHoa;
                cmbVatTuHangHoa.DisplayColumn = "Ten";
                cmbVatTuHangHoa.ValueColumn = "ID";
                cmbVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
                cmbVatTuHangHoa.AddVisibleColumn("Ten", "Tên");
                cmbVatTuHangHoa.Buttons[1].Visible = false;
                #endregion
            }
            catch
            {
            }
        }

        private void cmbDoiTuongNghiepVu_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                cmbDoiTuongNghiepVu.EditValue = null;
        }
        protected override void PrepareDataForReport()
        {
            DoiTuongNghiepVu selectedDoiTuongNghiepVu = null;
            if (cmbDoiTuongNghiepVu.EditValue is Guid && (Guid)cmbDoiTuongNghiepVu.EditValue != Guid.Empty)
            {
                selectedDoiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuongNghiepVu.EditValue);
            }
            else
            {
                MessageBox.Show("Phải chọn đối tượng nghiệp vụ");
                cmbDoiTuongNghiepVu.Focus();
            }

            VatTuHangHoa selectedVatTuHangHoa = null;
            if (cmbVatTuHangHoa.EditValue is Guid || cmbVatTuHangHoa.Text != "")
            {
                selectedVatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID((Guid)cmbVatTuHangHoa.EditValue);
            }


            BasicForms.FrmProgressBarDev.StartShowProgress();

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            ReportTemplates.Khac.BaoCaoHangTheoNhaCungCap.DsBaoCaoHangTheoNhaCungCap ds = new ReportTemplates.Khac.BaoCaoHangTheoNhaCungCap.DsBaoCaoHangTheoNhaCungCap();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                SqlDataAdapter da = null;

                cmd.CommandText = "Select_ThongTinDoanhNghiep2";
                cmd.Parameters.Clear();
                da = new SqlDataAdapter(cmd);
                da.Fill(ds.ThongTinDoanhNghiep);

                DataTable dtChiTietTongHopNhapXuatTon = ds.ChiTietBaoCaoTongHopHangKyGui;
                dtChiTietTongHopNhapXuatTon.Rows.Add(dtChiTietTongHopNhapXuatTon.NewRow());
                dtChiTietTongHopNhapXuatTon.Rows[0]["KyBaoCao"] = _KyBaoCao.Ten;
                dtChiTietTongHopNhapXuatTon.Rows[0]["TenNhaCungCap"] = selectedDoiTuongNghiepVu.Ten;

                ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(_KyBaoCao.ThoiDiemDau);
                if (thoiDiemKhoaSoGanNhat == null) throw new GeneralLibs.CustomException("Không có thời điểm khóa sổ trước " + _KyBaoCao.ThoiDiemDau.ToString());


                DataTable dtKhoanMucBaoCaoTongHopHangKyGui = ds.KhoanMucBaoCaoTongHopHangKyGui;
                if (selectedVatTuHangHoa == null)
                {
                    cmd.CommandText = "SELECT DISTINCT C.VatTuHangHoa1ID VatTuHangHoaID, D.Ma MaVatTuHangHoa, D.Ten TenVatTuHangHoa, D.DonViTinh, D.GiaBia \n" +
                                        "FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n"+
                                        "               INNER JOIN KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID \n"+
                                        "               INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID \n"+
                                        "WHERE C.VatTuHangHoa1ID IS NOT NULL \n" +
                                        "   AND A.LoaiChungTuID IN (SELECT ID FROM LoaiChungTu WHERE Ma IN ('HoaDonMuaHang', 'HangMuaTraLai'))\n" +
                                        "     AND A.DoiTuongNghiepVu1ID = @DoiTuongNghiepVuID \n" +
                                        "   AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi";
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("DoiTuongNghiepVuID", selectedDoiTuongNghiepVu.ID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", _KyBaoCao.ThoiDiemDau);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", _KyBaoCao.ThoiDiemCuoi);
                    da = new SqlDataAdapter(cmd);
                    DataTable dtHangHoaCoGiaoDich = new DataTable();
                    da.Fill(dtHangHoaCoGiaoDich);

                    for(int i=0;i< dtHangHoaCoGiaoDich.Rows.Count; i++)
                    {
                        DataRow khoanMucRow = dtKhoanMucBaoCaoTongHopHangKyGui.NewRow();

                        Guid vatTuHangHoaID = (Guid)dtHangHoaCoGiaoDich.Rows[i]["VatTuHangHoaID"];

                        khoanMucRow["MaVatTuHangHoa"] = dtHangHoaCoGiaoDich.Rows[i]["MaVatTuHangHoa"];
                        khoanMucRow["TenVatTuHangHoa"] = dtHangHoaCoGiaoDich.Rows[i]["TenVatTuHangHoa"];
                        khoanMucRow["DonViTinh"] = dtHangHoaCoGiaoDich.Rows[i]["DonViTinh"];
                        khoanMucRow["GiaBia"] = dtHangHoaCoGiaoDich.Rows[i]["GiaBia"];

                        TonKho phatSinhNhap = TonKho.CalculatePhatSinhNhapTheoNhaCungCap(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoaID);
                        khoanMucRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                        khoanMucRow["GiaTriNhap"] = phatSinhNhap.ThanhTien;

                        TonKho phatSinhXuatBan = TonKho.CalculatePhatSinhXuatBanMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoaID);
                        khoanMucRow["SoLuongXuat"] = phatSinhXuatBan.SoLuong;
                        khoanMucRow["GiaTriXuat"] = phatSinhXuatBan.SoLuong * (decimal)khoanMucRow["GiaBia"];

                        TonKho phatSinhXuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoaID);
                        khoanMucRow["SoLuongXuatTra"] = phatSinhXuatTra.SoLuong;
                        khoanMucRow["GiaTriXuatTra"] = phatSinhXuatTra.ThanhTien;

                        TonKho phatSinhXuatKhac = TonKho.CalculatePhatSinhXuatLyDoKhac(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoaID);
                        khoanMucRow["SoLuongXuatKhac"] = phatSinhXuatKhac.SoLuong;
                        khoanMucRow["GiaTriXuatKhac"] = phatSinhXuatKhac.ThanhTien;

                        TonKho tonCuoiKy = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoaID);
                        khoanMucRow["SoLuongCuoiKy"] = phatSinhNhap.SoLuong - phatSinhXuatBan.SoLuong - phatSinhXuatTra.SoLuong - phatSinhXuatKhac.SoLuong;
                        khoanMucRow["GiaTriCuoiKy"] = (decimal)khoanMucRow["SoLuongCuoiKy"] * phatSinhNhap.DonGia;

                        dtKhoanMucBaoCaoTongHopHangKyGui.Rows.Add(khoanMucRow);

                        BasicForms.FrmProgressBarDev.Status = string.Format("Đã xử lý {0}/{1} thuốc", i, dtHangHoaCoGiaoDich.Rows.Count);
                    }
                }
                else
                {
                    VatTuHangHoa vatTuHangHoa = selectedVatTuHangHoa;

                    DataRow khoanMucRow = dtKhoanMucBaoCaoTongHopHangKyGui.NewRow();
                    khoanMucRow["MaVatTuHangHoa"] = vatTuHangHoa.Ma;
                    khoanMucRow["TenVatTuHangHoa"] = vatTuHangHoa.Ten;
                    khoanMucRow["DonViTinh"] = vatTuHangHoa.DonViTinh;
                    khoanMucRow["GiaBia"] = vatTuHangHoa.GiaBia;

                    TonKho phatSinhNhap = TonKho.CalculatePhatSinhNhapTheoNhaCungCap(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                    khoanMucRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                    khoanMucRow["GiaTriNhap"] = phatSinhNhap.ThanhTien;

                    TonKho phatSinhXuatBan = TonKho.CalculatePhatSinhXuatBanMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoa.ID);
                    khoanMucRow["SoLuongXuat"] = phatSinhXuatBan.SoLuong;
                    khoanMucRow["GiaTriXuat"] = phatSinhXuatBan.SoLuong * vatTuHangHoa.GiaBia;

                    TonKho phatSinhXuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                    khoanMucRow["SoLuongXuatTra"] = phatSinhXuatTra.SoLuong;
                    khoanMucRow["GiaTriXuatTra"] = phatSinhXuatTra.ThanhTien;

                    TonKho phatSinhXuatKhac = TonKho.CalculatePhatSinhXuatLyDoKhac(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoa.ID);
                    khoanMucRow["SoLuongXuatKhac"] = phatSinhXuatKhac.SoLuong;
                    khoanMucRow["GiaTriXuatKhac"] = phatSinhXuatKhac.ThanhTien;

                    TonKho tonCuoiKy = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                    khoanMucRow["SoLuongCuoiKy"] = phatSinhNhap.SoLuong - phatSinhXuatBan.SoLuong - phatSinhXuatTra.SoLuong - phatSinhXuatKhac.SoLuong;
                    khoanMucRow["GiaTriCuoiKy"] = (decimal)khoanMucRow["SoLuongCuoiKy"] * phatSinhNhap.DonGia;

                    dtKhoanMucBaoCaoTongHopHangKyGui.Rows.Add(khoanMucRow);
                }

                _Report = new ReportTemplates.Khac.BaoCaoHangTheoNhaCungCap.RptBaoCaoTongHopHangTheoNhaCungCap();
                _Report.SetDataSource(ds);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }

            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }
        protected override void PrintReport()
        {
            if (_Report != null)
            {
                ReportTemplates.FrmPrintReport frm = new ReportTemplates.FrmPrintReport(_Report, "Tổng hợp tồn theo nhà cung cấp");
                frm.Show();
            }
        }
    }
}
